package com.iseastar.guojiang.cabinet.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.iseastar.guojiang.BaseActivity;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.model.CabinetBean;
import com.shouhuobao.station.R;
import com.shouhuobao.take.utils.StringUtils;
import com.shouhuobao.take.weight.CircularImage;

import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import droid.frame.activity.base.BaseAdapterWithImage;
import droid.frame.utils.lang.Str;

/**
 * 接驳任务-二级列表
 *
 * @author coffee <br>
 *         2016-8-3上午11:32:26
 */
@SuppressLint("SimpleDateFormat")
public class ServicePointAdapter extends BaseAdapterWithImage<CabinetBean.StationCabubetBean> {
    //包裹数量不为0的时候调用
    private String tipStr = "<font color=#4a4a4a>包裹数量 </font><font color=#D0021B>{0}</font>";
    //包裹数量为0的时候调用
    private String tipStrColor = "<font color=#B3B3B3>包裹数量 {0}</font>";
    private BDLocation mBdLocation;
    private boolean isBaiduMapInstall = false;
    //包裹数量为0的时候颜色的显示
    private String emptyParcelCountColor = "#B3B3B3";

    public BDLocation getmBdLocation() {
        return mBdLocation;
    }

    public void setmBdLocation(BDLocation mBdLocation) {
        this.mBdLocation = mBdLocation;
    }

    public ServicePointAdapter(ArrayList<CabinetBean.StationCabubetBean> items, Activity context, ListView listView) {
        super(items, context, listView);
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        if (packageInfos != null) {
            for (PackageInfo packageInfo : packageInfos) {
                if (packageInfo.packageName.equals("com.baidu.BaiduMap")) {
                    isBaiduMapInstall = true;
                    break;
                }
            }
        }
        setEmptyView(R.layout.app_order_empty);
    }

    public ServicePointAdapter(ArrayList<CabinetBean.StationCabubetBean> items, Activity context, BDLocation bdLocation, ListView listView) {
        super(items, context, listView);
        this.mBdLocation = bdLocation;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (hasEmptyView()) {
            return super.getView(position, convertView, parent);
        }
        ViewHolder holder;
        if (convertView == null || convertView.getTag() == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.cabinet_main_item, parent, false);
            holder.type = (TextView) convertView.findViewById(R.id.service_point_type);
            holder.name = (TextView) convertView.findViewById(R.id.service_point_name);
            holder.addr = (TextView) convertView.findViewById(R.id.service_point_address);
            holder.orderNum = (TextView) convertView.findViewById(R.id.service_point_parcel_num);
            holder.navigation = convertView.findViewById(R.id.service_point_nav);
            // 驿站信息
            holder.stationPhone = (TextView) convertView.findViewById(R.id.service_point_phone);
            holder.stationServiceTime = (TextView) convertView.findViewById(R.id.service_point_time);
            holder.stationCall = convertView.findViewById(R.id.service_point_call);
            holder.outtimeNum = (TextView) convertView.findViewById(R.id.service_outtime_num);
            holder.photoImg = (CircularImage) convertView.findViewById(R.id.photo_img);
            holder.photoIcon = (ImageView) convertView.findViewById(R.id.photo_icon);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        final CabinetBean.StationCabubetBean item = items.get(position);
        // 驿站
        if (item.isStation()) {
            holder.type.setText("驿站");
            holder.name.setText(item.getName());
            //
            ((ViewGroup) holder.stationPhone.getParent()).setVisibility(View.VISIBLE);
            holder.stationCall.setVisibility(View.VISIBLE);
            if (StringUtils.isEmpty(item.getPhone())) {
                holder.stationPhone.setText("电话: ");
            } else {
                holder.stationPhone.setText("电话: " + item.getPhone());
            }
            holder.stationServiceTime.setText("营业时间: " + item.getBusiTime());
            if (StringUtils.isEmpty(item.getHeadImage())) {
                holder.photoImg.setVisibility(View.GONE);
                holder.photoIcon.setVisibility(View.VISIBLE);
                holder.photoIcon.setImageResource(R.drawable.icon_cabinet);
            } else {
                holder.photoIcon.setVisibility(View.GONE);
                holder.photoImg.setVisibility(View.VISIBLE);
                showImage(item.getHeadImage(), holder.photoImg, null);
                holder.photoImg.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogMgr.showLargeStationPhoto(context, item.getHeadImage());
                    }
                });
            }
        } else {// 柜子
            holder.photoImg.setVisibility(View.GONE);
            holder.photoIcon.setVisibility(View.VISIBLE);
            // 隐藏电话、和服务时间
            ((ViewGroup) holder.stationPhone.getParent()).setVisibility(View.GONE);
            // 隐藏拨号
            holder.stationCall.setVisibility(View.GONE);
            //
            holder.type.setText("智能柜");
            holder.name.setText(item.getName() + "");
            //            holder.name.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_station, 0, 0, 0);
            holder.photoIcon.setImageResource(R.drawable.icon_station);
        }
        //包裹数量是0的时候变成灰色
        if (Str.isEmpty(item.getOrderCount()) || "0".equals(item.getOrderCount())) {
            holder.name.setTextColor(Color.parseColor(emptyParcelCountColor));
            holder.addr.setTextColor(Color.parseColor(emptyParcelCountColor));
            holder.stationPhone.setTextColor(Color.parseColor(emptyParcelCountColor));
            holder.stationServiceTime.setTextColor(Color.parseColor(emptyParcelCountColor));
            holder.outtimeNum.setTextColor(Color.parseColor(emptyParcelCountColor));
            holder.orderNum.setText(Html.fromHtml(MessageFormat.format(tipStrColor, item.getOrderCount())));
        } else {
            holder.orderNum.setText(Html.fromHtml(MessageFormat.format(tipStr, item.getOrderCount())));
        }

        //包裹超期数量
        if (item.getOrderCount2() > 0) {
            holder.outtimeNum.setText("(" + item.getOrderCount2() + "个包裹已超期)");
            holder.outtimeNum.setVisibility(View.VISIBLE);
        } else {
            holder.outtimeNum.setVisibility(View.GONE);
        }

        holder.addr.setText("地址: " + item.getAddress());
        holder.navigation.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = getBaiduIntentUri(item);
                if (intent != null) {
                    context.startActivity(intent);
                } else {
                    ((BaseActivity) context).showToast("请安装百度地图");
                }
            }
        });
        holder.stationCall.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + item.getPhone()));
                context.startActivity(intent);
            }
        });
        return convertView;
    }

    private class ViewHolder {
        TextView type;// 驿站|快递柜
        TextView name, orderNum, addr;
        TextView stationPhone, stationServiceTime, outtimeNum;
        View navigation, stationCall;
        CircularImage photoImg;//驿站头像加载控件
        ImageView photoIcon;//柜子头像加载或者驿站没有头像的时候加载
    }

    private String getDistance(String latitude, String longitude) {
        return null;
    }

    public Intent getBaiduIntentUri(CabinetBean.StationCabubetBean item) {
        Intent intent = null;
        if (isBaiduMapInstall) {
            // BdLocation通过Handler发送
            String uri = null;
            // 导航
            if (mBdLocation != null) {
                String format = "intent://map/direction?origin=latlng:{0},{1}" + //
                        "|name:我的位置&destination={2},{3}&mode=driving&region={4}" + //
                        "&src={5}#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end";
                uri = MessageFormat.format(format, mBdLocation.getLatitude(), mBdLocation.getLongitude(), //
                        item.getLatitude(), item.getLongitude(), mBdLocation.getCity(), context.getPackageName());
            } else {
                // 定位
                String format = "intent://map/marker?location={0},{1}&title={2}&content={3}&src={4}" + //
                        "#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end";
                uri = MessageFormat.format(format, item.getLatitude(), item.getLongitude(), item.getCommunity(), item.getAddress(), context.getPackageName());
            }
            try {
                intent = Intent.parseUri(uri, Intent.URI_INTENT_SCHEME);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        } else {
            ((BaseActivity) context).showToast("请安装百度地图");
        }
        return intent;
    }
}
